<template>
  <div>
      <Card title="批量新增-管理信息" :bordered="false" dis-hover class="ivu-mt i-table-no-border">
        <Row class="card-title action_bar_wrap" justify="end" type="flex">
          <Col v-if="showBtn('关联商品')">
            <el-button class="action_bar_btn_color" type="text" @click="handleAssociatedGoods">关联商品</el-button>
          </Col>
          <Col v-if="baseTableData.length>0">
            <el-button class="action_bar_btn_color" type="text" @click="handleExportData" :loading="exportLoading">模板导出</el-button>
          </Col>
          <Col>
            <a><Upload
              class="action_bar_upload"
              :show-upload-list="false"
              :format="['xlsx','xls','csv']"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-format-error="handleUploadFormatError"
              :before-upload="handleBeforeUpload"
              :action="uploadBaseURL+'sysback/batch/prepare/allmanaging/saveAllManagingToPage'"
            >模板导入</Upload></a>
          </Col>
          <Col v-if="baseTableData.length>0">
            <el-button class="action_bar_btn_color" type="text" @click="handleSubmitData" :loading="submitLoading">提交</el-button>
          </Col>
        </Row>
        <Row class="format_table_wrap">
          <general-render-table
            :loading="spuTableLoading"
            :data-source="baseTableData"
            :columns="manageTableColumns"
            @handleCancelSelect="handleCancelSelect"
            @handleChangeCheckBox="handleChangeCheckBox"
            @handleChangeRadio="handleChangeRadio"
          />
        </Row>
      </Card>
      <!--第三方平台-->
      <Modal v-model="platModal"
             width="70%"
             title="请选择第三方平台"
             @on-ok="closeModal('0')"
             @on-cancel="closeModal('0')">
        <Card dis-hover>
          <Form :label-width="120">
            <Table :columns="platCol"
                   border
                   :data="platData"
                   height="300"
                   @on-selection-change='platChange' />
          </Form>
        </Card>
      </Modal>
    <spu-associated-dialog
      ref="spuModal"
      :columns="associatedGoodsTableColumns"
      :requestApi="requestApi"
      :requestParams="requestParams"
      :distinctParams="distinctParams"
      @getRowList="getAssociatedGoodsAction"
    ></spu-associated-dialog>
  </div>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage'
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission'
/* components */
import spuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog'
import generalRenderTable from '@/pages/commodity/modules/components/generalRenderTable'
/* mixins */
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension'
/* constants */
import { requiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension'
import { ADD_MANAGE_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import { getAttributeTypeFn } from '@/pages/commodity/modules/utils'
import { getDealManageDataToApiFn } from '@/pages/commodity/modules/utils/manageInfoRequireUtils'
export default {
  mixins: [spuDimensionMixins],
  components: { spuAssociatedDialog, generalRenderTable },
  data () {
    return {
      exportLoading: false, // 导出按钮loading
      submitLoading: false, // 提交按钮loading
      requestApi: {
        url: ['/sysback/batch/prepare/allmanaging/getProductList'], // 关联商品查询接口
        type: 'post'
      },
      requestParams: requiredParams.requestParams, // 关联商品查询接口所需入参
      distinctParams: requiredParams.distinctParams, // 关联商品查询接口区别未关联和已关联的入参
      associatedGoodsTableColumns: [ // 关联商品弹框表格columns
        { type: 'selection', width: 60, align: 'center' },
        { title: '商品名称', key: 'productNameFinal', width: 150 },
        { title: 'SPU编码', key: 'spuNo', width: 180 },
        { title: '商品分类', key: 'categoryPath', width: 180 },
        { title: '管理区域', key: 'manageAreaName', width: 180 },
        { title: '规格参数', key: 'saleAttrInfo', width: 150 },
        { title: '品牌', key: 'brandName', width: 150 },
        { title: '操作', slot: 'action', align: 'center', fixed: 'right', minWidth: 100 }
      ],
      linshiBaseTableData: [], // 列表的数据源
      baseTableData: [], // 列表的数据源
      manageTableColumns: [], // 表格columns
      spuTableLoading: false, // 表格数据加载loading
      notShowAttrList: ['logistics_stock', 'manage_distributing_centre', 'manage_packlist'], // 无需渲染的表格列
      initManageTableColumns: [ // 表格初始columns
        {
          title: '品类',
          key: 'categoryPath',
          width: 120
        },
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 120
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          width: 120
        },
        {
          title: '品牌',
          key: 'brandName',
          width: 120
        }
      ],
      platModal: false,
      platDataOnce: [],
      platData: [],
      thirdPlatList: [], // 第三方平台
      platCol: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '平台名称',
          key: 'platName',
          minWidth: 120
        },
      ],
      apiObj: {
        commitBasicInfo: {
          url: '/sysback/batch/prepare/allmanaging/commitAllManaging', // 提交接口地址
          type: 'post' // 接口请求类型
        },
        exportPageToExcelPost: {
          url: '/sysback/batch/prepare/allmanaging/exportPageToExcelPost', // 表单导出接口地址
          type: 'post' // 接口请求类型
        },
        getThirdListClean: {
          url: '/sysback/update/product/allmanaging/getThirdListClean', // 查所有第三方平台接口地址（没有分页，全部是未勾选）
          type: 'post'
        },
      }
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', [
      'showBtn'
    ]),
  },
  mounted () {
    this.manageTableColumns = _.cloneDeep(this.initManageTableColumns)
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList')
  },
  methods: {
    /* 初始化表格数据 */
    initBaseTableDataFn () {
      this.manageTableColumns = _.cloneDeep(this.initManageTableColumns)
      this.baseTableData = [];
      this.handleDealTableTh()
      this.manageTableColumns.push({
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right'
      })
    },
    /* 处理表头方法 */
    handleDealTableTh () {
      let dataList = this.linshiBaseTableData.reduce((value, item, index) => {
        let { productUuid, productNameFinal, brandName, categoryPath, spuNo, saleAttrInfo, manageArea } = item.main
        value.push({ productUuid, productNameFinal, brandName, categoryPath, spuNo, saleAttrInfo, manageArea })
        let nameList = Object.keys(item)
        let notForEachName = ['authDepartments', 'thirdPlatList', 'cityList']
        nameList.forEach(nameType => {
          if (!_.isArray(item[nameType]) || notForEachName.includes(nameType)) { return }
          value[index][nameType] = []
          item[nameType].forEach(thItem => {
            if (thItem.attrType === '04') {
              thItem.valueName = thItem.valueName ? _.clone(thItem.valueName).split(/,|，|\s+/) : [] // 以中英文逗号、空格（一个或多个）分割字符串
            }
            value[index][thItem.attrUuid] = thItem
            value[index][nameType].push(thItem.attrUuid)
            if (index === 0 && !this.notShowAttrList.includes(thItem.attrUuid)) {
              this.manageTableColumns.push({
                title: thItem.attrName,
                align: 'center',
                key: thItem.attrUuid,
                type: getAttributeTypeFn(thItem.attrType),
                required: thItem.attrMust === '1' || false,
                disabled: thItem.canEdit === 'N' || false,
                width: thItem.attrType === '04' ? '180' : '140'
              })
            }
          })
        })
        return value
      }, [])
      this.baseTableData = _.cloneDeep(dataList)
    },
    /* 据归类UUID，查询税类代码taxCateNo、销售税率taxRate */
    getTaxInfoDataAction (data) {
      let { allValueOptions, val } = data
      let target = _.find(allValueOptions, item => { return item.optionHtml === val })
      let uuid = target.optionValue
      let params = { uuid }
      return new Promise((resolve, reject) => {
        this.spuTableLoading = true
        ApiRequest(`/sysback/addsingleproduct/basicinfo/getClassificationByUuid?uuid=${uuid}`, 'post', params).then(res => {
          this.spuTableLoading = false
          if (res.retStatus !== '1') { return }
          let data = {
            taxCateNo: res.retData.taxCateNo,
            taxRate: res.retData.taxRate
          }
          resolve(data)
        }).catch(() => {
          this.spuTableLoading = false
        })
      })
    },
    /* 处理单选下拉逻辑 */
    handleChangeRadio (data) {
      let { row, val, columnName } = data
      if (columnName === 'tax_classify') { // 如果当前切换的是归类名称字段，就调用归类信息接口
        this.getTaxInfoDataAction({ val, allValueOptions: row.tax_classify.allValueOptions }).then(res => {
          if (!res) { return }
          row.tax_code.valueName = res.taxCateNo
          row.tax_rate.valueName = res.taxRate
        })
      }
    },
    /* 处理多选下拉逻辑 */
    handleChangeCheckBox (data) {
      let { row, val, columnName } = data
      const notSaleFlag = val.includes('不销售')
      const notSaleIndex = val.indexOf('不销售')
      if (notSaleFlag) {
        if (val.length === notSaleIndex + 1) {
          row[columnName].valueName = ['不销售']
        } else {
          row[columnName].valueName.splice(notSaleIndex, 1)
        }
      } else {
        row[columnName].valueName = val
      }
    },
    /* 取消对应表格row */
    handleCancelSelect (data) {
      let { row } = data
      this.handleDeleteSpuRow(row, this.baseTableData, 'productUuid')
      this.getAssociatedGoodsAction()
    },
    /* 关联商品 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品')
      sessionStorage.setItem('buttonId', curBtnId)
      this.CHANGE_MODAL_SWITCH(true)
      /* this.$nextTick(() => {
        this.$refs.spuModal.getDataListAction()
      }) */
    },
    /* 关联商品获取表格数据 */
    getAssociatedGoodsAction () {
      let dataList = this.getListFromMapFn().map(value => {
        return value.uuid
      })
      // let data = {
      //   productUuidList: dataList.join(','),
      // }
      let data = dataList
      if (dataList.length !== 0) {
        this.spuTableLoading = true
        ApiRequest(`/sysback/batch/prepare/allmanaging/queryAllManagingList`, 'post', data, false).then(res => {
          this.spuTableLoading = false
          if (res.retStatus === '1') {
            this.linshiBaseTableData = res.retData;
            this.initBaseTableDataFn();
          }
        }).catch(() => {
          this.spuTableLoading = false
        })
      } else {
        this.linshiBaseTableData = []
        this.baseTableData = []
      }
    },
    /* 提交数据 */
    handleSubmitData () {
      if (this.baseTableData.length > ADD_MANAGE_INFO_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${ADD_MANAGE_INFO_AMOUNT}`)
      }
      let { submitResults, errorMessage } = getDealManageDataToApiFn({ tableData: this.baseTableData, type: 'add', notShowAttrList: this.notShowAttrList })
      if (errorMessage) { return this.$Message.warning(errorMessage) }
      let { url, type } = this.apiObj.commitBasicInfo
      this.submitLoading = true
      ApiRequest(url, type, submitResults, false).then(res => {
        this.submitLoading = false
        if (res.retStatus === '1') {
          this.$Message.success('提交成功');
          this.baseTableData = [];
          this.linshiBaseTableData = [];
          this.$router.push({ name: 'commodityNotPerfection' }) // 跳转待准入页面
        }
      }).catch(() => {
        this.submitLoading = false
      })
    },
    /* 导出数据 */
    handleExportData () {
      let { submitResults } = getDealManageDataToApiFn({ tableData: this.baseTableData, type: 'add', notShowAttrList: this.notShowAttrList })
      let { url, type } = this.apiObj.exportPageToExcelPost
      this.exportLoading = true
      ApiRequestExportTable(url, type, submitResults, false).then(res => {
        this.exportLoading = false
        const blob = new Blob([res], {
          type: 'application/octet-stream',
        });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '批量维护管理信息.xlsx';
        link.click();
        window.URL.revokeObjectURL(blob); // 释放掉blob对象
      }).catch(() => {
        this.exportLoading = false
        this.$Message.error('导出失败');
      });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.spuTableLoading = false
      this.$Message.error('格式错误')
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.spuTableLoading = true
      this.linshiBaseTableData = [];
      this.baseTableData = [];
    },
    /* 上传成功 */
    handleUploadSuccess (file) {
      this.spuTableLoading = false
      if (file.retStatus === '1') {
        // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
        this.linshiBaseTableData = file.retData;
        this.initBaseTableDataFn();
      } else {
        // 如果接口返回失败,就打印失败信息
        this.$Message.error(file.retMessage)
      }
    },
    /* 上传失败 */
    handleUploadError () {
      this.spuTableLoading = false
      this.$Message.error('上传失败');
    },
    getThirdListCleanOnce () {
      // 查询第三方列表，只查一次
      ApiRequest(this.apiObj.getThirdListClean.url,
        this.apiObj.getThirdListClean.type, {}, false).then(res => {
        if (res.retStatus === '1' && res.retData !== null) {
          this.platDataOnce = res.retData.thirdList;
        }
      })
    },
    // 弹出第三方平台，回显勾选
    getThirdListClean () {
      // 克隆一份数据
      this.platData = JSON.parse(JSON.stringify(this.platDataOnce));
      // 回显勾选
      if (this.baseTableData[this.selectIndex].thirdPlatList !== null &&
        this.baseTableData[this.selectIndex].thirdPlatList !== undefined) {
        this.platData.forEach(itme => {
          this.baseTableData[this.selectIndex].thirdPlatList.forEach(element => {
            if (itme.platCode === element) {
              itme._checked = true;
            }
          });
        });
      }
      this.platModal = true;
    },
    // 第三方平台勾选监听
    platChange (selectedList) {
      this.thirdPlatList = []; // 清空以前的勾选
      selectedList.forEach(item => {
        this.thirdPlatList.push(item.uuid);
      });
      this.baseTableData[this.selectIndex].thirdPlatList = this.thirdPlatList;
    },
  }
}
</script>
<style lang="less" scoped>
.image {
  width: 100%;

  img {
    width: 100%;
  }
}

.div {
  display: flex;

  > span:nth-of-type(2),
  > span:nth-of-type(3) {
    margin-left: 20px;
  }
}

.a {
  background: #5d8ae3 !important;

  > div {
    border-left: 40px solid #5d8ae3 !important;
  }
}

.b {
  background: #5d8ae3 !important;

  > div:nth-of-type(1) {
    border-left: 40px solid #5d8ae3 !important;
  }

  > div:nth-of-type(2) {
    position: absolute;
    top: 0px;
    left: -20px;
    border-top: 20px solid #5d8ae3 !important;
    border-right: 0px solid #5d8ae3 !important;
    border-bottom: 20px solid #5d8ae3 !important;
  }
}
</style>
